package com.first.xiinn.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.first.core.Constants;
import com.first.core.service.impl.BaseServiceImpl;
import com.first.core.util.PagingBean;
import com.first.module.acm.dao.AppUserDao;
import com.first.module.acm.model.AppUser;
import com.first.xiinn.dao.InMessageDao;
import com.first.xiinn.dao.ShortMessageDao;
import com.first.xiinn.model.InMessage;
import com.first.xiinn.model.ShortMessage;
import com.first.xiinn.service.ShortMessageService;

public class ShortMessageServiceImpl extends BaseServiceImpl<ShortMessage>
  implements ShortMessageService
{
  private ShortMessageDao messageDao;

  @Resource
  private InMessageDao inMessageDao;

  @Resource
  private AppUserDao appUserDao;

  public ShortMessageServiceImpl(ShortMessageDao dao)
  {
    super(dao);
    this.messageDao = dao;
  }

  public List<ShortMessage> findAll(String userId, PagingBean pb)
  {
    return this.messageDao.findAll(userId, pb);
  }

  public List<ShortMessage> findByUser(String userId)
  {
    return this.messageDao.findByUser(userId);
  }

  public List searchShortMessage(String userId, ShortMessage shortMessage, Date from, Date to, PagingBean pb)
  {
    return this.messageDao.searchShortMessage(userId, shortMessage, from, to, pb);
  }

  public ShortMessage save(String senderId, String receiveIds, String content, Short msgType)
  {
    ShortMessage shortMessage = new ShortMessage();
    shortMessage.setContent(content);
    AppUser curUser = (AppUser)this.appUserDao.get(senderId);
    shortMessage.setSender(curUser.getFullname());
    shortMessage.setSenderId(curUser.getUserId());
    shortMessage.setSendTime(new Date());

    this.messageDao.save(shortMessage);

    String[] reIds = receiveIds.split("[,]");
    if (reIds != null)
    {
      for (String userId : reIds) {
        InMessage inMsg = new InMessage();
        inMsg.setDelFlag(Constants.FLAG_UNDELETED);
        inMsg.setReadFlag(InMessage.FLAG_UNREAD);
        inMsg.setShortMessage(shortMessage);
        AppUser receiveUser = (AppUser)this.appUserDao.get(userId);

        inMsg.setUserId(receiveUser.getUserId());
        inMsg.setUserFullname(receiveUser.getFullname());
        this.inMessageDao.save(inMsg);
      }
    }

    return shortMessage;
  }
}

